Skip to main content

谈谈 Redux

是什么

Redux 是 JavaScript 状态管理容器,提供可预测化的状态管理,解决了组件间的状态共享问题,实现了多组件通信,也是一种 MVC 机制。

核心概念

  1. View 组件状态改变时,通过store.dispatch()将 action 传到 store。

  2. Action 生成一个描述状态变化的 action 对象,并传递给 store,它是 store 数据的唯一来源。

  3. Store 接收 action 对象并传递给 reducer,驱动 reducer 执行状态更新任务,更新后刷新 dom 节点(即 view 中执行 render)。 Store 就是保存数据的地方,你可以把它看成一个容器。整个应用只能有一个 Store。

  4. Reducer Reducer 是一个函数,它接受 Action 和当前 State 作为参数,更新组件状态,并将新的状态值 State 返回 store

单向数据流

说出常用 API

  • store.dispatch(action)
  • store.getState()

两个常见的中间件

redux-thunk redux-promise

怎么用

预览地址

action.js

构建 action,通过创建一个函数,然会返回一个对象,注意需要携带 type 属性

const sendAction = () => {
return {
type: "send_type",
value: "我是一个action",
};
};

export default sendAction;

reducer.js

构建 reducer,用来响应 action,然后通过 return 把数据传回给 store

const initState = {
value: "默认值"
};
const reducer = (state = initState, action) => {
switch (action.type) {
case "send_type":
return Object.assign({}, state, action);
default:
return state;
}
};
export default reducer;

store.js

利用 createStore 来构建 store,构建的时候传递我们写好的 reducer 中 state

import { createStore } from "redux";
// 导入我们自己创建的reducer
import reducer from "./reducer";
// 构建 store
const store = createStore(reducer);
export default store;

App.js

//App.js
import React from "react";
import Home from "./Home";

function App() {
return (
<div className="App">
<Home></Home>
</div>
);
}
export default App;

Home.js

  1. 利用 store.subscribe()注册监听
  2. 当我们利用 store.dispatch()发送一个 action 的时候就能触发我们的监听了,在里面利用 store.getState()就能拿到值
// src/page/home/index.js
import React from "react";
import sendAction from "./action";
// redux
import store from "./store";

export default class Home extends React.Component {
onClick = () => {
const action = sendAction();
console.log(action);
store.dispatch(action);
};

// 必须添加监听器
componentDidMount() {
// subscribe 监听
store.subscribe(() => {
this.setState({});
});
}

render() {
return (
<>
<button onClick={this.onClick}>改变默认值</button>
<div>{store.getState().value}</div>
</>
);
}
}

参考文章